package com.another.bidservice.service.impl

import com.another.bidservice.dao.jpa.ColumnJPADao
import com.another.bidservice.dao.jpa.FormJPADao
import com.another.bidservice.dao.mapper.FormDao
import com.another.bidservice.entity.TForm
import com.another.bidservice.service.CommonService
import com.another.bidservice.utils.util.sql.Factory
import com.another.common.utils.Page
import com.another.common.utils.common.EmptyUtil
import com.another.common.utils.result.Result
import org.apache.log4j.Logger
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.math.BigInteger

@Service
@Transactional
open class CommonServiceImpl : CommonService {

    private val logger = Logger.getLogger(this.javaClass)

    @Autowired
    private val formDao: FormDao? = null

    @Autowired
    private val formJPADao: FormJPADao? = null

    @Autowired
    private val columnJPADao: ColumnJPADao? = null



    override fun publicAPI(form: TForm?): Result? {
        val page =
            Page<Map<String, String>?>()

        if (EmptyUtil.isEmpty(form!!.formId)) {
            return Result.error("formId必传!")
        }

        //获取需要显示的列和sql
        val sql = formJPADao!!.findTopByFormId(form.formId)
        if (EmptyUtil.isEmpty(sql)) {
            return Result.error("formId是不是传错了!")
        }

        val columns = columnJPADao!!.findAllByFormId(form.formId)
        if (EmptyUtil.isEmpty(columns)) {
            return Result.error("没有查询到需要显示的字段!")
        }

        sql.columns = columns
        sql.page = form.page
        sql.length = form.length


        //查询总记录数
        val countSql = Factory.SqlCountFactory(sql)
        val count: Any = formDao!!.publicCountSql(countSql)
        sql.total = BigInteger(count.toString())

        //查询数据
        val dataSql = Factory.SqlDataFactory(sql)
        val data =
            formDao.publicSql(dataSql)

        if (EmptyUtil.isEmpty(data)) {
            return Result.setSuccessMsg("没有查询到数据!")
        }

        page.total = BigInteger(count.toString())
        page.totalPages = form.totalPages
        page.data = data
        return Result.success(page)
    }

}